import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import articleService from '@/services/articleService'
import { useAppStore } from './app'
import { useArticleStore } from './article'
import { logger } from '@/utils/logger';

export const useArticleDetailStore = defineStore('articleDetail', () => {
  const appStore = useAppStore()
  const articleStore = useArticleStore()
  
  // 状态数据
  const currentArticle = ref(null)
  const relatedArticles = ref([])
  const loading = ref(false)
  const error = ref(null)
  const navigationInfo = ref({
    prevArticle: null,
    nextArticle: null,
    currentIndex: -1,
    totalInChapter: 0
  })
  
  // 计算属性
  const articleTitle = computed(() => {
    return currentArticle.value?.title || ''
  })
  
  const articleContent = computed(() => {
    return currentArticle.value?.content || ''
  })
  
  const chapterInfo = computed(() => {
    if (!currentArticle.value) return null
    return {
      part: currentArticle.value.part,
      chapter: currentArticle.value.chapter,
      chapterPath: currentArticle.value.chapter_path,
      chapterHierarchy: currentArticle.value.chapter_hierarchy
    }
  })
  
  const keywords = computed(() => {
    if (!currentArticle.value?.keywords) return []
    return Array.isArray(currentArticle.value.keywords) 
      ? currentArticle.value.keywords 
      : currentArticle.value.keywords.split(' ').filter(k => k.trim())
  })
  
  const isFavorited = computed(() => {
    if (!currentArticle.value) return false
    // 添加防御性检查，确保 favorites 数组存在
    if (!articleStore.favorites || !Array.isArray(articleStore.favorites)) {
      console.warn('[ArticleDetail] articleStore.favorites 未初始化或不是数组')
      return false
    }
    return articleStore.favorites.some(
      fav => fav.article_number === currentArticle.value.article_number
    )
  })
  
  // 操作方法
  async function loadArticle(articleId) {
    console.log('🔍 [ArticleDetail] 开始加载条文:', articleId)
    loading.value = true
    error.value = null
    
    try {
      // 使用articleService获取条文详情
      console.log('🧪 [ArticleDetail] 调用articleService获取条文...')
      
      const response = await articleService.getArticle(articleId)
      console.log('🔬 [ArticleDetail] Service响应:', response)
      
      if (response && response.success && response.data) {
        console.log('✅ [ArticleDetail] 成功获取数据!')
        currentArticle.value = response.data
        console.log('💾 [ArticleDetail] 条文数据设置完成:', currentArticle.value.article_number)
        
        // 延迟加载相关条文和导航信息
        setTimeout(() => {
          Promise.all([
            loadRelatedArticles(response.data.part, response.data.chapter),
            loadNavigationInfo(articleId)
          ]).catch(err => {
            console.warn('加载相关信息失败:', err)
          })
        }, 100)
      } else {
        throw new Error('API响应格式错误')
      }
      
    } catch (err) {
      console.error('💥 [ArticleDetail] 加载失败:', err.message)
      error.value = err.message
      appStore.setError(`获取条文详情失败: ${err.message}`)
    } finally {
      loading.value = false
      console.log('🏁 [ArticleDetail] 加载完成，loading状态:', loading.value)
    }
  }
  
  async function loadRelatedArticles() {
    if (!currentArticle.value) return
    
    try {
      const { part, chapter } = currentArticle.value
      const response = await articleService.getArticlesByChapter(
        part, 
        chapter, 
        { page: 1, per_page: 10 }
      )
      
      // 过滤掉当前条文，只显示其他相关条文
      relatedArticles.value = response.articles.filter(
        article => article.article_number !== currentArticle.value.article_number
      ).slice(0, 6) // 最多显示6个相关条文
      
    } catch (err) {
      console.warn('获取相关条文失败:', err)
    }
  }
  
  async function loadNavigationInfo() {
    if (!currentArticle.value) return
    
    try {
      const { part, chapter } = currentArticle.value
      const response = await articleService.getArticlesByChapter(
        part, 
        chapter, 
        { page: 1, per_page: 100 } // 获取整章的条文用于导航
      )
      
      const articles = response.articles
      const currentIndex = articles.findIndex(
        article => article.article_number === currentArticle.value.article_number
      )
      
      navigationInfo.value = {
        prevArticle: currentIndex > 0 ? articles[currentIndex - 1] : null,
        nextArticle: currentIndex < articles.length - 1 ? articles[currentIndex + 1] : null,
        currentIndex: currentIndex + 1, // 显示用（从1开始）
        totalInChapter: articles.length
      }
      
    } catch (err) {
      console.warn('获取导航信息失败:', err)
    }
  }
  
  async function toggleFavorite() {
    if (!currentArticle.value) return
    
    try {
      if (isFavorited.value) {
        await articleStore.removeFromFavorites(currentArticle.value.article_number)
      } else {
        await articleStore.addToFavorites(currentArticle.value)
      }
    } catch (err) {
      appStore.setError(`操作收藏失败: ${err.message}`)
    }
  }
  
  function shareArticle() {
    if (!currentArticle.value) return
    
    const shareData = {
      title: `${currentArticle.value.article_number} - 民法典`,
      text: currentArticle.value.title,
      url: window.location.href
    }
    
    // 始终降级到复制链接
    navigator.clipboard.writeText(window.location.href).then(() => {
      appStore.addNotification({ type: 'success', message: '链接已复制到剪贴板！' });
      console.log('链接已复制到剪贴板');
    }).catch(() => {
      appStore.addNotification({ type: 'error', message: '复制链接失败，请手动复制。' });
      console.warn('分享失败，请手动复制链接');
    });
  }
  
  function navigateToArticle(articleNumber) {
    // 这个方法会被组件调用来导航到其他条文
    return `/article/${encodeURIComponent(articleNumber)}`
  }
  
  function reset() {
    currentArticle.value = null
    relatedArticles.value = []
    loading.value = false
    error.value = null
    navigationInfo.value = {
      prevArticle: null,
      nextArticle: null,
      currentIndex: -1,
      totalInChapter: 0
    }
  }
  
  return {
    // 状态
    currentArticle,
    relatedArticles,
    loading,
    error,
    navigationInfo,
    
    // 计算属性
    articleTitle,
    articleContent,
    chapterInfo,
    keywords,
    isFavorited,
    
    // 方法
    loadArticle,
    loadRelatedArticles,
    loadNavigationInfo,
    toggleFavorite,
    shareArticle,
    navigateToArticle,
    reset
  }
})
